import {Component, OnInit} from '@angular/core';
import {USER} from '../../../../../_mock/user';
import {Globals} from "../../../globals";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ApiUrl} from "../../../config/api-url";
import {BaseService} from "../../../shared/service/base.service";
import {PageHelper} from "../../../utils/page-helper-model";
import {ActivatedRoute, Router} from "@angular/router";
import {RoleIdEnum} from "../../../enums/role-id.enum";
import {UserInfoModel} from "../../../models/user-info.model";
import {Consts} from '../../../config/consts';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.less']
})
export class UserComponent implements OnInit {

  isMobile = Globals.isMobile();
  listOfData: any;
  listTickData: any;
  // 分页
  pageHelper: PageHelper = new PageHelper;
  formModel: FormGroup;
  selectedValue: null;
  // 运营商
  userList: [];
  // 门店
  merchantStoreList: [];

  memberStatistic: any;
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
  };
  // 用户信息
  userInfo: UserInfoModel;
  showTickets: boolean;

  constructor(private fb: FormBuilder, private baseService: BaseService, private activatedRoute: ActivatedRoute, private router: Router) {
    // this.listOfData = USER;
    this.buildForm();
    this.activatedRoute.queryParams.subscribe(params => {
      if (params['merchantStoreId'] != null) {
        this.formModel.get("merchantStoreId").setValue(params['merchantStoreId']);
        this.listOfData = [];
        this.getAgentsData();
      }else if (params['memberId']!=null){
        this.formModel.get("memberId").setValue(params['memberId']);
        this.listOfData = [];
        this.getAgentsData();
      } else {
        this.getAgentsData();
      }
    });
  }

  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    this.getAllUserOfName();
    this.findAllMerchantStoreByUserInfo();
    // this.findMerchantStatistic();
  }

  buildForm() {
    this.formModel = this.fb.group({
      userId: ['', []],
      merchantStoreId: ['', []],
      memberId: ['', []],
      nickName: ['', []],
      keyword: ['', []],
    });
  }
  onPageSizeChange(pageSize: any){
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
  }
  getAgentsData() {
    this.baseService.findListByMuchCondition(ApiUrl.MemberUrl + '/list', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.listOfData = data.data.list;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  getAllUserOfName() {
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName').subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  findAllMerchantStoreByUserInfo() {
    let userId = null;
    if (this.formModel.get("userId").value != null) {
      userId = this.formModel.get("userId").value;
    } else {
      userId = '';
    }
    this.baseService.get(ApiUrl.MerchantStoreUrl + '/findAllMerchantStoreByUserInfo?userId=' + userId).subscribe(
      data => {
        if (data.status == 0) {
          this.merchantStoreList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  gainUserId($event: any) {
    this.findAllMerchantStoreByUserInfo();
  }

  submitForm() {
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
    // this.findMerchantStatistic();
  }

  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.getAgentsData();
  }

  skipMerchant(data: any) {
    this.router.navigateByUrl('/merchant?userId=' + data.userId,
      {skipLocationChange: true});
  }

  skipAgency(data) {
    this.router.navigateByUrl('/agency?agencyNo=' + data.agencyNo,
      {skipLocationChange: true});
  }

  findMerchantStatistic() {
    this.baseService.findListByMuchCondition(ApiUrl.MemberUrl + '/findMerchantStatistic', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
            this.memberStatistic = data.data;
          // this.pageHelper.totalItems = data.data.total;
          // this.listOfData = data.data.list;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  showTicketsModel(data): void{
    this.showTickets = true;
    let params = {
      memberId: data.id,
      merchantStoreId: data.merchantStoreId
    };
    this.baseService.post(ApiUrl.TicketRecordUrl + '/findByMemberId', params).subscribe(
      data => {
        if (data.status == 0) {
          this.listTickData = data.data;
          console.log(this.listTickData)
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  handleOk(): void {
    console.log('Button ok clicked!');
    this.showTickets = false;
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.showTickets = false;
  }
  onClickTick(data){
    this.showTickets = false;
// 使用setTimeout延迟执行路由跳转
    setTimeout(() => {
      this.router.navigateByUrl('/ticket-usage-record?ticketRecordId=' + data.id, {skipLocationChange: true});
    }, 500); // 0.5秒后执行
  }
}
